import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button, List, Card, Empty, Badge, Tabs } from 'antd';
import { ArrowLeftOutlined, GiftOutlined, HistoryOutlined } from '@ant-design/icons';
import { getUserInfo } from '../../utils/storage';
import { getUserPointsHistory, POINTS_DESC, giveSignInPoints } from '../../utils/points';
import './PointsCenter.css';

const { TabPane } = Tabs;

const PointsCenter = () => {
  const navigate = useNavigate();
  const [userInfo, setUserInfo] = useState(null);
  const [pointsHistory, setPointsHistory] = useState([]);
  const [canSignIn, setCanSignIn] = useState(true);
  const [signInLoading, setSignInLoading] = useState(false);
  const [showAnimation, setShowAnimation] = useState(false);

  useEffect(() => {
    loadData();
    checkSignInStatus();
  }, []);

  const loadData = () => {
    const user = getUserInfo();
    setUserInfo(user);
    
    if (user) {
      const history = getUserPointsHistory();
      setPointsHistory(history);
    }
  };

  const checkSignInStatus = () => {
    const lastSignIn = localStorage.getItem('last_sign_in');
    const today = new Date().toDateString();
    
    if (lastSignIn === today) {
      setCanSignIn(false);
    }
  };

  const handleSignIn = async () => {
    setSignInLoading(true);
    
    // 模拟签到过程
    setTimeout(() => {
      const newPoints = giveSignInPoints();
      if (newPoints !== false) {
        localStorage.setItem('last_sign_in', new Date().toDateString());
        setCanSignIn(false);
        setShowAnimation(true);
        loadData();
        
        // 动画结束后重置状态
        setTimeout(() => {
          setShowAnimation(false);
        }, 1000);
      }
      setSignInLoading(false);
    }, 800);
  };

  const formatTime = (timestamp) => {
    return new Date(timestamp).toLocaleString('zh-CN');
  };

  const getPointsColor = (points) => {
    return points > 0 ? '#52c41a' : '#ff4d4f';
  };

  const pointsRules = [
    { title: '新用户注册', points: '+100积分', desc: '完成注册即可获得' },
    { title: '每日签到', points: '+5积分', desc: '连续签到获得更多奖励' },
    { title: '完成订单', points: '¥500=1积分', desc: '确认收货后获得' },
    { title: '商品评价', points: '+10积分', desc: '对购买商品进行评价' }
  ];

  if (!userInfo) {
    return (
      <div className="points-center">
        <div className="points-header">
          <Button 
            type="text" 
            icon={<ArrowLeftOutlined />}
            onClick={() => navigate(-1)}
          />
          <span className="header-title">积分中心</span>
        </div>
        <div style={{ padding: '40px 16px', textAlign: 'center' }}>
          <Empty description="请先登录" />
          <Button 
            type="primary" 
            onClick={() => navigate('/app/login')}
            style={{ marginTop: '16px' }}
          >
            去登录
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="points-center">
      {/* 头部导航 */}
      <div className="points-header">
        <Button 
          type="text" 
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate(-1)}
        />
        <span className="header-title">积分中心</span>
      </div>

      {/* 积分余额卡片 */}
      <div className={`points-balance-card ${showAnimation ? 'sign-in-success' : ''}`}>
        <div className="balance-info">
          <div className={`balance-amount ${showAnimation ? 'points-jump' : ''}`}>
            {userInfo.points || 0}
          </div>
          <div className="balance-label">可用积分</div>
          <div className="balance-desc">
            可抵扣 ¥{((userInfo.points || 0) * 0.01).toFixed(2)}
          </div>
        </div>
        <div className="balance-actions">
          <Button 
            type="primary" 
            icon={<GiftOutlined />}
            onClick={handleSignIn}
            disabled={!canSignIn}
            loading={signInLoading}
            size="small"
          >
            {canSignIn ? '签到领积分' : '今日已签到'}
          </Button>
        </div>
      </div>

      <Tabs defaultActiveKey="history" className="points-tabs">
        <TabPane tab="积分明细" key="history">
          {pointsHistory.length === 0 ? (
            <div style={{ padding: '40px 16px', textAlign: 'center' }}>
              <Empty 
                description="暂无积分记录"
                image={Empty.PRESENTED_IMAGE_SIMPLE}
              />
            </div>
          ) : (
            <List
              dataSource={pointsHistory}
              renderItem={item => (
                <List.Item className="points-history-item">
                  <div className="history-info">
                    <div className="history-title">{item.description}</div>
                    <div className="history-time">{formatTime(item.createTime)}</div>
                  </div>
                  <div 
                    className="history-points"
                    style={{ color: getPointsColor(item.points) }}
                  >
                    {item.points > 0 ? '+' : ''}{item.points}
                  </div>
                </List.Item>
              )}
            />
          )}
        </TabPane>

        <TabPane tab="积分规则" key="rules">
          <div className="points-rules">
            <div className="rules-header">
              <h3>如何获得积分？</h3>
              <p>完成以下任务即可获得相应积分奖励</p>
            </div>
            
            {pointsRules.map((rule, index) => (
              <Card key={index} size="small" className="rule-card">
                <div className="rule-content">
                  <div className="rule-info">
                    <div className="rule-title">{rule.title}</div>
                    <div className="rule-desc">{rule.desc}</div>
                  </div>
                  <Badge 
                    count={rule.points} 
                    style={{ backgroundColor: '#52c41a' }}
                  />
                </div>
              </Card>
            ))}
            
            <div className="rules-footer">
              <h3>积分使用说明</h3>
              <ul>
                <li>100积分 = 1元，可在下单时抵扣现金</li>
                <li>单笔订单最多可使用订单金额10%的积分</li>
                <li>积分不可转让，仅限本账户使用</li>
                <li>积分有效期为获得后的12个月</li>
                <li>订单完成获得积分：订单金额¥500=1积分（最少1积分）</li>
              </ul>
            </div>
          </div>
        </TabPane>
      </Tabs>
    </div>
  );
};

export default PointsCenter; 